const YEAR_COEFFICIENT = (24 * 3600 * 1000 * 365.25);

export const yearDiff = function (timeDiff, decimalNum = 1) {

    let diff = timeDiff / YEAR_COEFFICIENT;
    let d = Math.pow(10, decimalNum);
    return Math.floor(diff * d) / d;
}

export const charLength = function (str) {
    var len = 0;
    if (str) {
        for (var i = 0; i < str.length; i++) {
            var c = str.charCodeAt(i);
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f))
                len += 1;
            else
                len += 2;
        }
    }
    return len;
}

export const delayLoop = ({
    loopFun = ((index)=> {
    }), callbackFun = (()=> {
}), times = 10, millisec = 5000, auto = true
}) => {
    let index = 0;

    const nextLoop = function () {
        index++;
        if (index < times) {
            onceLoop();
        } else {
            callbackFun();
        }
        return index;
    }

    function onceLoop() {
        loopFun(index);
        if (auto) {
            setTimeout(()=> {
                nextLoop();
            }, millisec);
        }
    }

    onceLoop(0);

    return {nextLoop};
}

export const getRandomColor = ({lower=0, upper=255})=> {
    lower = (lower < 0) ? 0 : lower;
    upper = (255 < upper) ? 255 : upper;

    let r = parseInt(lower + Math.random() * (upper - lower)).toString(16);
    let g = parseInt(lower + Math.random() * (upper - lower)).toString(16);
    let b = parseInt(lower + Math.random() * (upper - lower)).toString(16);

    return '#' + r + g + b;
}

export const shuffleArray = (array)=> {
    for (var j, x, i = array.length; i; j = parseInt(Math.random() * i), x = array[--i], array[i] = array[j], array[j] = x);
    return array;
}

export const dateFormat = (date, fmt)=> {

    var o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds(),
        "q+": Math.floor((date.getMonth() + 3) / 3),
        "S": date.getMilliseconds()
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}